<template>
  <el-dialog
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :title="$t('crm.components.376c813c7d178312f6f44efa7206e04d')"
    custom-class="no-padding-dialog"
    width="800px">
    <span slot="title" class="el-dialog__title">
      {{ $t('crm.components.892916698a7c2a73fc14b3059a649904') }}
      <i
        v-if="helpObj"
        class="wk wk-icon-fill-help wk-help-tips"
        :data-type="helpObj.type"
        :data-id="helpObj.id" />
    </span>
    <div
      v-loading="loading"
      :class="{ 'show-table': showTable }"
      class="duplicate-check">
      <div>
        <el-input
          v-model="searchContent"
          class="search-input"
          @keyup.enter.native="getList">
          <el-select slot="prepend" v-model="typeSelect">
            <el-option
              :label="$t('crm.components.2c69b35ae4312fb7e6844bed0e651ceb')"
              value="name" />
            <el-option
              :label="$t('crm.components.7835e0862b3ee94f4d2c1e3c1aabf61a')"
              value="phone" />
          </el-select>
          <el-button
            slot="append"
            type="primary"
            icon="wk wk-search"
            @click.native="getList">
            {{ $t('crm.components.2c9794bb9f4a4e826b4b0fc7887a122a') }}
          </el-button>
        </el-input>
      </div>

      <el-table
        v-if="showTable"
        :data="tableData"
        :cell-class-name="cellClassName"
        class="duplicate-check__content"
        border
        height="380"
        style="width: 100%;"
        @row-click="handleRowClick">
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          show-overflow-tooltip>
          <template slot-scope="{ row, column }">
            <wx-open-data v-if="column.property === 'ownerUserName'" :openid="row.ownerUserName" />
            <template v-else>{{ row[column.property] }}</template>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          width="110px"
          :label="$t('crm.components.a7e92e72cb36b2555cb41b4f24f3740d')">
          <template slot-scope="scope">
            <el-button
              type="primary-text"
              style="padding: 0;"
              :disabled="scope.row.type == 3 || !scope.row.poolAuthList || !scope.row.poolAuthList.receive"
              @click="handleClick('receive', scope.row)">{{ $t('crm.components.50090803f9c86d27bf78a4f42e638f9e') }}</el-button>
            <el-button
              type="primary-text"
              style="padding: 0;"
              :disabled="scope.row.type == 3 || !scope.row.poolAuthList ||!scope.row.poolAuthList.distribute"
              @click="handleClick('distribute', scope.row)">{{ $t('crm.components.aaa90c18d510ba11eca10f0d33268bd9') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="showTable" class="duplicate-check__footer">
        {{ $t('crm.components.71091aaa0aa8246a386b9c28d9eb5a1f') }}
      </div>

      <c-r-m-full-screen-detail
        :id="relationId"
        :visible.sync="showFullDetail"
        :crm-type="relationCrmType"
        :pool-id="poolId"
        @handle="getList" />

      <alloc-handle
        :pool-id="poolId"
        :selection-list="[relationData]"
        :dialog-visible.sync="allocDialogShow"
        :crm-type="relationCrmType"
        @handle="getList" />
    </div>
  </el-dialog>
</template>

<script>
import {
  crmCustomerDataCheckAPI,
  crmCustomerReceiveAPI
} from '@/api/crm/customer'
import {
  crmLeadsReceiveAPI
} from '@/api/crm/leads'

import AllocHandle from '../SelectionHandle/AllocHandle' // 公海分配操作

import crmTypeModel from '@/views/crm/model/crmTypeModel'

export default {
  name: 'DuplicateCheck',
  components: {
    AllocHandle,
    CRMFullScreenDetail: () =>
      import('@/components/CRMFullScreenDetail')
  },
  props: {
    crmType: String,
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      typeSelect: 'name',
      searchContent: '',
      tableData: null,

      showFullDetail: false, // 查看相关客户管理详情
      relationId: '', // 相关ID参数
      relationData: {}, // 关联数据
      poolId: '', // 公海Id
      relationCrmType: '', // 相关类型
      allocDialogShow: false //  分配弹窗
    }
  },
  computed: {
    showTable() {
      return this.tableData
    },

    isCustomerFilter() {
      return this.typeSelect == 'name'
    },

    // 客户名称、创建时间、负责人、最后跟进时间、操作
    fieldList() {
      if (this.isCustomerFilter) {
        return [{
          prop: 'name',
          label: this.$t('crm.components.79bd408511a2eb64301458d65d315a45'),
          width: 200
        }, {
          prop: 'createTime',
          label: this.$t('crm.components.ec354d603bde607284de2d1c9b7f4190'),
          width: 160
        }, {
          prop: 'ownerUserName',
          label: this.$t('crm.components.3749fa3d946c3d0535a2b9c8dd830aee'),
          width: 100
        }, {
          prop: 'lastTime',
          label: this.$t('crm.components.e631ed10a027fc186f6b45c8f05c2f2d'),
          width: 160
        }, {
          prop: 'module',
          label: this.$t('crm.components.8c78693014e5d8bee5bdc79da3a92c1c'),
          width: 150
        }]
      }

      return [{
        prop: 'mobile',
        label: this.$t('crm.components.9e8d23209748a5dceba6708677fcd383'),
        width: 160
      }, {
        prop: 'contactsName',
        label: this.$t('crm.components.22b213bc0252a6679468377dd843f95e'),
        width: 160
      }, {
        prop: 'name',
        label: this.$t('crm.components.3e54905df5ac74f1e809dd61431735d2'),
        width: 200
      }, {
        prop: 'ownerUserName',
        label: this.$t('crm.components.ed261a41f27a1a3e0fb57171969639e7'),
        width: 100
      }, {
        prop: 'module',
        label: this.$t('crm.components.b197a4c40e519bc5f64083b584c87f98'),
        width: 100
      }]
    },

    // 帮助信息
    helpObj() {
      return {
        leads: {
          type: '7',
          id: '77'
        }, customer: {
          type: '8',
          id: '78'
        }, contacts: {
          type: '9',
          id: '79'
        }
      }[this.crmType] || null
    }
  },
  watch: {
    typeSelect() {
      this.searchContent = ''
      this.tableData = null
    }
  },
  mounted() {},
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
      this.resetData()
    },

    resetData() {
      this.typeSelect = 'name'
      this.searchContent = ''
      this.tableData = null
    },

    getList() {
      if (!this.searchContent) {
        return
      }
      const params = {}
      params[this.typeSelect] = this.searchContent
      this.loading = true
      crmCustomerDataCheckAPI(params).then(res => {
        this.loading = false
        const list = res.data || []
        this.tableData = list.map(item => {
          item.module = crmTypeModel.convertTypeToName(item.type)
          // 如果在公海，以公海名称展示
          if (item.poolList && item.poolList.length > 0) {
            item.module = {
              1: '线索池',
              2: '公海',
              3: '公海'
            }[item.type]
          }
          if (item.poolName) {
            item.module = `${item.module}（${item.poolName}）`
          }
          // 是手机号
          if (!this.isCustomerFilter) {
            item.mobile = this.searchContent
            if (item.type == crmTypeModel.contacts) {
              // item.contactsName = item.name
              // item.contactsId = item.id

              // item.name = item.customerName
              // item.id = item.customerId
              // name 字段对应的点击类型 以type为准，所以将type校准为客户
              // 联系人详情 已 contactsId 为准
              // item.type = crmTypeModel.customer
            }
          }

          return item
        })
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 列表点击
     */
    handleRowClick(row, column, event) {
      if (column.property == 'name' && row.id) {
        this.relationId = row.id
        if (row.poolAuthList) {
          this.poolId = row.poolAuthList.poolId
        } else {
          this.poolId = ''
        }

        this.relationCrmType = row.type == 3 ? 'customer' : crmTypeModel.convertTypeToKey(row.type)
        this.showFullDetail = true
      } else if (column.property == 'contactsName' && row.contactsId) {
        this.relationId = row.contactsId
        this.relationCrmType = 'contacts'
        this.showFullDetail = true
      }
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'name' || column.property === 'contactsName') {
        return 'can-visit--underline'
      } else {
        return ''
      }
    },

    handleClick(type, data) {
      if (type === 'receive') {
        const message = {
          1: '确定要领取该线索吗?',
          2: this.$t('crm.components.a719fe6692de84dba518640c7ea3392d')
        }[data.type]
        this.$confirm(message, this.$t('crm.components.c9e5a94af51a1e73cc60a56b065b448e'), {
          confirmButtonText: this.$t('crm.components.0ca9e58dc5b9fe02f96b85a757b01161'),
          cancelButtonText: this.$t('crm.components.e59644907c69df1576bacbe17c2c1b28'),
          type: 'warning'
        })
          .then(() => {
            const request = {
              1: crmLeadsReceiveAPI,
              2: crmCustomerReceiveAPI
            }[data.type]
            request({
              ids: [data.id],
              poolId: data.poolAuthList.poolId
            })
              .then(res => {
                this.$message.success(this.$t('crm.components.b2892734cedadfe51ff844978467f69c'))
                this.getList()
              })
              .catch(() => {})
          })
          .catch(() => {})
      } else {
        const typeName = crmTypeModel.convertTypeToKey(data.type)
        data[`${typeName}Id`] = data.id
        this.relationCrmType = typeName
        this.relationData = data
        this.allocDialogShow = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.duplicate-check {
  position: relative;
  padding: 20px;
  padding-bottom: 40px;

  &__content {
    margin-top: 15px;
  }

  &__footer {
    margin-top: 8px;
  }
}

.duplicate-check.show-table {
  padding-bottom: 20px;
}

.el-input {
  ::v-deep .el-select .el-input {
    width: 130px;

    ::v-deep i {
      font-weight: bold;
    }
  }

  ::v-deep .el-input-group__append {
    color: white;
    background-color: $--color-primary;
    border-color: $--color-primary;

    .el-button {
      ::v-deep i {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}
</style>
